package com.rt.gptnext.controller;

import com.rt.gptnext.common.bean.HttpResult;
import com.rt.gptnext.data.dto.CompletionDto;
import com.rt.gptnext.data.entity.OpenaiChat;
import com.rt.gptnext.data.entity.OpenaiCompletion;
import com.rt.gptnext.manager.OpenaiManager;
import com.rt.gptnext.service.OpenaiChatService;
import com.rt.gptnext.service.OpenaiCompletionService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author gaoyiyang
 */
@RestController
@RequestMapping("/api")
public class ApiController {

    @Value("${app.version:}")
    private String version;

    @Resource
    private OpenaiManager openaiManager;

    @Resource
    private OpenaiChatService openaiChatService;

    @Resource
    private OpenaiCompletionService openaiCompletionService;

    @RequestMapping
    public HttpResult<String> index() {
        return HttpResult.success("version: " + version);
    }

    @DeleteMapping("/removeCompletion")
    public HttpResult<Void> removeCompletion(Long id, String qaId) {
        openaiCompletionService.remove(qaId, id);
        return HttpResult.success();
    }

    @DeleteMapping("/removeChat")
    public HttpResult<Void> removeChat(@RequestParam Long id) {
        openaiChatService.remove(id);
        return HttpResult.success();
    }

    @PostMapping("/initChat")
    public HttpResult<OpenaiChat> initChat(@RequestBody OpenaiChat chat) {
        return HttpResult.success(openaiChatService.initChat(chat));
    }

    @PostMapping("/completion")
    public void completion(@RequestBody CompletionDto completionDto, HttpServletResponse response) {
        openaiManager.completion(completionDto, response);
    }

    @PostMapping("/resetCompletion")
    public void resetCompletion(@RequestBody CompletionDto completionDto, HttpServletResponse response) {
        openaiManager.resetCompletion(completionDto, response);
    }

    @PostMapping("/continueCompletion")
    public void continueCompletion(@RequestBody CompletionDto completionDto, HttpServletResponse response) {
        openaiManager.continueCompletion(completionDto, response);
    }

    @GetMapping("/chats")
    public HttpResult<List<OpenaiChat>> chats() {
        return HttpResult.success(openaiChatService.chats());
    }

    @GetMapping("/completions")
    public HttpResult<List<OpenaiCompletion>> completions(@RequestParam Long chatId, @RequestParam Integer version) {
        return HttpResult.success(openaiCompletionService.completions(chatId, version));
    }

}
